﻿using ETA.Common;
using ETA.Entity;
using ETA.EntityMappings;
using FluentNHibernate.Automapping;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using FluentNHibernate.Conventions.Helpers;
using NHibernate;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ETA
{
    public class NHibernateHelper
    {
        private static  readonly ISessionFactory _sessionFactory;

        static NHibernateHelper()
        {
            _sessionFactory = GetSessionFactory();
        }

        private static ISessionFactory GetSessionFactory()
        {
            var runModel = Config.RunModel;
            var dbKey = "ETALocal";
            if (runModel == "1")
            {
                dbKey = "ETARemote";
            }
            var cfg = new ETAAutoMapConfiguration();
            var sessionFactory = Fluently.Configure()
                .Database(MsSqlConfiguration.MsSql2008.ConnectionString(c => c.FromConnectionStringWithKey(dbKey)).ShowSql())
                 .Mappings(m =>
                 {
                     m.AutoMappings.Add(AutoMap.AssemblyOf<User>(cfg)); //User所在的程序集->自动映射 //
                     m.FluentMappings.AddFromAssemblyOf<UserMap>();//UserMap所在的程序集 ->手动映射
                 })
                   .BuildSessionFactory();
            return sessionFactory;
        }

        public static ISession GetSession()
        {
            ISession session = _sessionFactory.OpenSession();
            return session;
        }


    }
}
